package demo.module_main.p;

import android.os.Environment;

import java.io.File;

import demo.module_main.contract.ISplashContract;
import demo.module_main.net.response.VersionInfo;
import demo.module_main.net.IMainApi;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import library.base.BaseApplication;
import library.base.mvp.presenter.BasePresenter;
import library.base.mvp.presenter.event.BaseEvent;
import library.common.util.NetworkUtil;
import library.net.RxRetrofitUtils;
import library.net.retrofit.IBaseApi;
import library.net.retrofit.download.IRxProgressListener;
import library.net.retrofit.entity.FileEntity;
import library.net.retrofit.observer.RxObserver;
import module.common.net.Schedulers;

/**
 * @author Created by qiang.hou on 2018/12/4.
 * @version 1.0
 */
public class SplashPresenter extends BasePresenter implements ISplashContract.IPresenter {
    public static final long DELAY_TIME = 3000;//延时进入下一个页面的最短时间

    public static final String ACTION_SHOW_SPLASH_CONTENT = "action_show_splash";
    public static final String ACTION_CHECK_VERSION = "action_check_app_version";
    public static final String ACTION_DOWNLOAD_APK = "action_download_apk";
    public static final String ACTION_UPDATE_PROGRESS_VERSION = "action_download_apk_progress_version";

    private final String DEFAULT_SAVE_FILE_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator + "donut" + File.separator + "download" + File.separator;
    private final String DOWNLOAD_APK_FILE = "donut_update.apk";

    private Disposable downloadDisposable;

    @Override
    public void doInitProcess() {
    }

    @Override
    public void doCheckVersion(String versionName, String deviceId) {

        if (!NetworkUtil.isNetworkAvailable(BaseApplication.getContext())) {
            postEvent(DELAY_TIME, ACTION_SHOW_SPLASH_CONTENT);
            return;
        }
        final long startTime = System.currentTimeMillis();
        RxRetrofitUtils.getInstance()
                .create(IMainApi.class)
                .version(versionName, deviceId)
                .compose(Schedulers.<VersionInfo>response_data2())
                .compose(Schedulers.<VersionInfo>io_main())
                .subscribe(new RxObserver<VersionInfo>() {
                    @Override
                    public void onNext(VersionInfo versionInfo) {
                        if (versionInfo.isNewVersion()) {
                            postEvent(versionInfo, System.currentTimeMillis() - startTime, ACTION_CHECK_VERSION);
                        } else {
                            postEvent(System.currentTimeMillis() - startTime, ACTION_SHOW_SPLASH_CONTENT);
                        }
                    }

                    @Override
                    protected void doError(Throwable e) {
                        postEvent("获取版本号失败!" + e.getMessage(), BaseEvent.ACTION_TAG_RESPONSE_ERROR);
                        postEvent(System.currentTimeMillis() - startTime, ACTION_SHOW_SPLASH_CONTENT);
                    }
                });
    }

    @Override
    public void doUpdateVersion(String apkDownloadUrl) {
        FileEntity fileEntity = new FileEntity();
        fileEntity.url = apkDownloadUrl;
        fileEntity.completedBytes = 0L;
        fileEntity.destFileDir = DEFAULT_SAVE_FILE_PATH;
        fileEntity.destFileName = DOWNLOAD_APK_FILE;
        RxRetrofitUtils.getInstance().rxDownloadCall(
                RxRetrofitUtils.getInstance().
                        create(IBaseApi.class).
                        downloadBigFile(fileEntity.url),
                fileEntity, new IRxProgressListener() {
                    @Override
                    public void onProgress(Object tag, long speed, long readLength, long totalLength) {
                        postEvent(new Long[]{readLength / 1024 / 1024, totalLength / 1024 / 1024}, ACTION_UPDATE_PROGRESS_VERSION);
                    }
                }, new Observer<File>() {
                    private Disposable d;

                    @Override
                    public void onSubscribe(Disposable d) {
                        this.d = d;
                        downloadDisposable = d;
                    }

                    @Override
                    public void onNext(File file) {
                        postEvent(file, ACTION_DOWNLOAD_APK);
                    }

                    @Override
                    public void onError(Throwable e) {
                        postEvent(null, ACTION_DOWNLOAD_APK);
                        if (null != d && !d.isDisposed()) {
                            d.dispose();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (null != d && !d.isDisposed()) {
                            d.dispose();
                        }
                    }
                });
    }

    @Override
    public void doCancelDownload() {
        if (null != downloadDisposable && !downloadDisposable.isDisposed()) {
            downloadDisposable.dispose();
        }
    }
}
